package youleche.com.sql.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import youleche.com.sql.business.BTableField;
import youleche.com.sql.business.BTableInfo;
import youleche.com.sql.model.MTableField;
import youleche.com.sql.model.MTableInfo;
import youleche.com.sql.servlet.common.ClassGenerateFactory;
import youleche.com.sql.servlet.common.SqlGenerateFactory;
import youleche.com.sql.servlet.common.SuperHttpServlet;
import youleche.com.util.DateUtil;
import youleche.com.util.JsonHelper;

/**
 * Servlet implementation class STableFieldServlet
 */
public class STableFieldServlet extends SuperHttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public STableFieldServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int action = Integer.parseInt(request.getParameter("action"));
		switch(action){
			case 0:
				//根据tableId获取字段
				this.getTableFieldsByTableId(request, response);
				break;
			case 1:
				//保存字段
				this.saveTableFields(request, response);
				break;
			case 2:
				//生成sql
				this.getTableSql(request, response);
				break;
			case 3:
				//生成表对象
				this.getTableObject(request, response);
				break;
			case 4:
				//添加备用字段
				this.addReadyField(request, response);
				break;
			case 5:
				//生成IDAO
				this.generateIdao(request, response);
				break;
		}
	}
	
	/**
	 * 生成IDAO
	 * @param request
	 * @param response
	 */
	private void generateIdao(HttpServletRequest request, HttpServletResponse response){
		try {			
			String tableId = request.getParameter("tableId");
			
			Map<String, String> keyValue = JsonHelper.readJsonKeyValues(request);
			Set<Map.Entry<String, String>> set = keyValue.entrySet();
			String path = "";
			String packages = "";
			int i =0;
			for (Iterator<Map.Entry<String, String>>  it = set.iterator(); it.hasNext();) {
				Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
				if("path".equals(entry.getKey())){
					path = entry.getValue();
				}
				
				if("packages".equals(entry.getKey())){
					packages = entry.getValue();
				}
				if(!"".equals(packages) && !"".equals(path)){
					break;
				}
			}
			
			if(!"".equals(packages) && !"".equals(path)){
				ClassGenerateFactory.generateIdao(path + "\\\\", tableId, null, packages);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 生成表对象
	 * @param request
	 * @param response
	 */
	private void getTableObject(HttpServletRequest request, HttpServletResponse response){
		BTableField handler = new BTableField();
		try {
			List<MTableField> fields = handler.getTableFieldsByTableId(request.getParameter("tableId"));
			if(fields != null && fields.size() > 0){
				super.response(response, this.generateTableObjectByFields(fields));
			}else{
				super.response(response, "");				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 生成sql
	 * @param request
	 * @param response
	 */
	private void getTableSql(HttpServletRequest request, HttpServletResponse response){
		BTableField handler = new BTableField();
		try {
			List<MTableField> fields = handler.getTableFieldsByTableId(request.getParameter("tableId"));
			if(fields != null && fields.size() > 0){
				super.response(response, this.generateSqlByFields(fields));
			}else{
				super.response(response, "");				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据字段生成sql
	 * @param fields 字段
	 * @return 返回sql
	 * @throws Exception 
	 */
	private String generateSqlByFields(List<MTableField> fields) throws Exception{
		return SqlGenerateFactory.generateSqlByFields(fields);
	}
	
	/**
	 * 根据字段生成sql
	 * @param fields 字段
	 * @return 返回sql
	 * @throws Exception 
	 */
	private String generateTableObjectByFields(List<MTableField> fields) throws Exception{
		return SqlGenerateFactory.generateObjectByFields(fields);
	}
	
	/**
	 * 保存字段
	 * @param request
	 * @param response
	 */
	private void saveTableFields(HttpServletRequest request, HttpServletResponse response){
		JSONObject jsonObj = JsonHelper.readJSONObject(request);
		MTableField tablefield = (MTableField)JSONObject.toBean(jsonObj, MTableField.class);
		BTableField handler = new BTableField();
		try {
			tablefield.setTableId(request.getParameter("tableId"));			
			List<MTableField> addlist = null;
			if(handler.isExistFieldByFieldEnglishNameAndTableId(tablefield.getFieldEnglishName(), request.getParameter("tableId"))){
				////更新
				handler.updateFieldByIdAndEnglishName(tablefield);
			}else{				
				addlist = new LinkedList<MTableField>();
				addlist.add(tablefield);				
				handler.addTableFields(addlist);				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据tableId获取字段
	 * @param tableId 表ID
	 * @return 返回所有字段
	 * @throws Exception 异常
	 */
	public void getTableFieldsByTableId(HttpServletRequest request, HttpServletResponse response){
		BTableField handler = new BTableField();
		try {
			JsonHelper.printObjectListToJsonStringForEasyUI(response, handler.getTableFieldsByTableId(request.getParameter("tableId")));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加备用字段
	 * @param request
	 * @param response
	 */
	private void addReadyField(HttpServletRequest request, HttpServletResponse response){		
		try {
			int size = Integer.parseInt("".equals(request.getParameter("size")) == true ? "0" : request.getParameter("size"));
			if(size ==0){
				return;
			}
			
			BTableField handler = new BTableField();
			List<MTableField> list = new LinkedList<MTableField>();
			String tableId = request.getParameter("tableId");
			int length = handler.getReadyFieldNum(tableId);
			int arg = 0;
			MTableField field = null;
			for(int i =0; i< size; i++){
				field = new MTableField();
				arg = length + i + 1; 
				field.setFieldAddTime(DateUtil.getDate("yyyy-MM-dd HH:mm:ss"));
				field.setFieldChineseName("备用字段" + arg);
				field.setFieldDesc("备用字段");
				field.setTableId(tableId);
				field.setFieldEnglishName("A" + arg);
				field.setFieldType("varchar");
				field.setFieldLength("200");
				field.setIsNull(0);
				list.add(field);
			}
			handler.addTableFields(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
